﻿using StandXunYouWeb.Model;
using StandXunYouWeb.Utility;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace StandXunYouWeb
{
    /// <summary>
    /// 用户是否已登录
    /// </summary>
    public class AuthorFilters : Attribute,IAuthorizationFilter
    {
        const string ResponseURL = "/Account/Login";
        public void OnAuthorization(AuthorizationFilterContext context)
        {
            var token = context.HttpContext.Request.Cookies["token"];

            if (string.IsNullOrWhiteSpace(token))
            {
                //无效的请求  没有token令牌
                context.Result = new RedirectResult(ResponseURL);
            }
            else
            {
                //验证用户Id 和 用户名是否为空
                try
                {
                    if(!Validate(token))
                    {
                        context.Result = new RedirectResult(ResponseURL);
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                    context.Result = new RedirectResult(ResponseURL);
                }
            }
        }

        /// <summary>
        /// 验证是否通过  
        /// </summary>
        /// <param name="token"></param>
        /// <returns>true 通过 false不通过</returns>
        public static bool Validate(string token)
        {
            var str = AESEncryptHelper.Decode(token);
            var model = JsonConvert.DeserializeObject<Users>(str);
            return model != null && !string.IsNullOrWhiteSpace(model.UserName) && !string.IsNullOrWhiteSpace(model.UserIds);
        }
        public static Users GetUserByToken(string token)
        {
            var str = AESEncryptHelper.Decode(token);
            if (!string.IsNullOrWhiteSpace(token))
            {
                var EmployeesModel = JsonConvert.DeserializeObject<Users>(str);
                return EmployeesModel;
            }
            return null;
        }
    }
}
